/*
 * pcf8563.c
 *
 *  Created on: Oct 27, 2016
 *      Author: duan
 */

#include "pcf8563.h"


/*--------------------------------------------------------------------------------------
 *  Struct
 *-------------------------------------------------------------------------------------*/
PCF8563_IIC pcf8563 =
		{ .write_byte = rtc_write_byte, .read_byte = rtc_read_byte };

static u8 rtc_read_byte(u16 addr) {

	u32 nTempVal = 0;
	u8 nReadVal;

	nTempVal = (0x1 << 31 | 0x1 << 24 | addr << 8 | 0x0);
	rRTC_CTRL = nTempVal;
	while (nTempVal & (0x1 << 31)) {
		nTempVal = rRTC_CTRL;
	}

	nTempVal = rRTC_READ;
	nReadVal = nTempVal & 0xff;
	udelay(2000000);

	return nReadVal;
}

static void rtc_write_byte(u16 addr, u8 data) {
	u32 nTempVal = 0;

	nTempVal = (0x1 << 31 | addr << 8 | data);
	rRTC_CTRL = nTempVal;
	while (nTempVal & (0x1 << 31)) {
		nTempVal = rRTC_CTRL;
	}
	udelay(1000);
}

void set_rtc_remote_time(u8 *Time) {
	pcf8563.write_byte(2, Time[5]); // rBCDSEC
	pcf8563.write_byte(3, Time[4]); // rBCDMIN
	pcf8563.write_byte(4, Time[3]); // rBCDHOUR
	pcf8563.write_byte(5, Time[2]); // rBCDDAY
	pcf8563.write_byte(7, Time[1]); // rBCDMON
	pcf8563.write_byte(8, Time[0]); // rBCDYEAR
}

void get_rtc_remote_time(u8 *Time) {

	Time[0] = pcf8563.read_byte(8);
	Time[1] = pcf8563.read_byte(7);
	Time[2] = pcf8563.read_byte(5);
	Time[3] = pcf8563.read_byte(4);
	Time[4] = pcf8563.read_byte(3);
	Time[5] = pcf8563.read_byte(2);

	Time[0] &= 0xff;
	Time[1] &= 0x1f;
	Time[2] &= 0x3f;
	Time[3] &= 0x3f;
	Time[4] &= 0x7f;
	Time[5] &= 0x7f;

	xil_printf(" *******  timestamp: 20%2d-%2d-%2d  %x:%x:%x .\r\n", Time[0],Time[1], Time[2], Time[3], Time[4], Time[5]);
}
